<template>
  <div class="bac">
    <!-- 版心 -->
    <div class="container">
      <!-- 登录表单 -->
      <van-form @submit="onSubmit" validate-first @failed="onFailed">
        <h1 class="zhuce-font">注册</h1>
        <van-field
          v-model="formData.uName"
          name="用户名"
          left-icon="/img/icon/my.png"
          placeholder="请输入用户名"
          :rules="[{ required: true, message: '用户名不能为空' }]"
        />
        <van-field
          v-model="formData.uEmail"
          name="邮箱"
          left-icon="/img/icon/email.png"
          placeholder="请输入邮箱"
          :rules="[
          {required: true, message: '邮箱不能为空' },
          {validator,message:'邮箱格式不正确'},
          {validator:asyncValidatorEmail,message:'该邮箱已存在'}]"
        />
        <van-field
          v-model="formData.uCode"
          name="验证码"
          left-icon="/img/icon/yzm.png"
          placeholder="请输入验证码"
          :rules="[
          {required: true, message: '验证码不能为空' },
          {validator:asyncValidatorCode,message:'验证码错误'}]"
        >
          <template #button>
            <van-button
              size="small"
              style="width:8.5rem;"
              type="primary"
              v-if="sendBtnMsg=='发送验证码'"
              @click="sendCode"
            >{{sendBtnMsg}}</van-button>
            <van-button
              size="small"
              style="width:8rem;"
              type="primary"
              v-else
              disabled
              @click="sendCode"
            >{{sendBtnMsg}}</van-button>
          </template>
        </van-field>
        <van-field
          v-model="formData.uPwd"
          type="password"
          name="密码"
          left-icon="/img/icon/pwd.png"
          placeholder="请输入密码"
          :rules="[{ required: true, message: '密码不能为空' }]"
        />
        <div style="margin: 16px;">
          <van-button type="primary" round block native-type="submit">注册</van-button>
          <van-button type="info" round block @click="goLogin">登录</van-button>
        </div>
      </van-form>
      <!-- 其他登录方式 -->
      <div class="zdy-bottom">
        <!-- 分割线 -->
        <van-divider style="margin:1rem 0">其他登录方式</van-divider>
        <van-grid :border="false" :column-num="3" icon-size="3rem" direction="horizontal">
          <van-grid-item icon="/img/icon/qq.png" />
          <van-grid-item icon="/img/icon/weibo.png" />
          <van-grid-item icon="/img/icon/chat.png" />
        </van-grid>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      sendBtnMsg: "发送验证码",
      // 邮箱规则
      emailPattern: /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/,
      // 存放表单数据
      formData: {
        uName: "",
        uEmail: "",
        uCode: "",
        uPwd: ""
      },
      timer: null
    };
  },
  methods: {
    /**
     * 跳转到登录
     */
    goLogin() {
      this.$router.push("/login");
    },
    /**
     * 发送验证码
     */
    sendCode() {
      if (this.formData.uEmail) {
        let time = 30; // 30秒
        new Promise(resolve => {
          clearInterval(this.timer);
          this.timer = setInterval(() => {
            if (time > 0) {
              this.sendBtnMsg = time + "秒";
              time--;
            } else {
              this.sendBtnMsg = "发送验证码";
            }
            resolve("发送验证码");
          }, 1000);
        }).then(res => {
          this.sendBtnMsg = res;
        });
        // 获取验证码
        this.http
          .post(this.$api.sendUserEmailCode, {
            email: this.formData.uEmail
          })
          .then(res => res.data)
          .then(res => {
            console.log("------", res);
            if (res.code == 200) {
              this.$msg.success("发送成功");
            } else {
              this.$msg.fail("发送失败");
            }
          });
      } else {
        this.$msg.fail("邮箱不能为空！");
      }
    },
    /**
     * 邮箱唯一性校验
     */
    validator(val) {
      return /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/.test(
        val
      );
    },
    // 异步校验邮箱返回 Promise
    asyncValidatorEmail(email) {
      let that = this;
      return new Promise(resolve => {
        that.http.post(that.$api.checkUserEmail, { email }).then(res => {
          console.log("邮箱唯一性校验返回：", res);
          if (res?.data?.code == 200) {
            resolve(true);
          } else {
            resolve(false);
          }
        });
      });
    },
    // 异步校验验证码 Promise
    asyncValidatorCode(code) {
      let that = this;
      return new Promise(resolve => {
        that.http
          .post(that.$api.checkUserCode, { email: this.formData.uEmail, code })
          .then(res => {
            console.log("验证码校验返回：", res);
            if (res?.data?.code == 200) {
              resolve(true);
            } else {
              resolve(false);
            }
          });
      });
    },
    // 注册
    onSubmit(values) {
      this.http
        .post(this.$api.register, this.formData)
        .then(res => res.data)
        .then(res => {
          if (res.code == 200) {
            this.$msg.success(res.msg);
            this.$router.replace("/login");
          } else {
            this.$msg.fail(res.msg);
          }
        });
    },
    onFailed(errorInfo) {
      console.log("failed", errorInfo);
    }
  }
};
</script>

<style lang="scss" scoped>
.bac {
  display: flex;
  height: 100vh;
  background: url("/public/img/background/reg_bg.jpg");
  background-color: #f7f7f7;
  background-size: 100vw 24rem;
  background-repeat: no-repeat;
}
.van-cell-group {
  border-radius: 1rem;
  border: none;
  padding: 4rem;
  margin-top: 6rem;
  clear: both;
}

.zdy-bottom {
  background-color: #f7f7f7;
}

.van-button--primary {
  background-color: #fecb1c;
  border: none;
}
.van-button--info {
  margin-top: 1rem;
  background-color: #ccc;
  border: none;
}

.van-field__control,
.van-field__error-message {
  margin-left: 2rem;
  background-color: #f7f7f7 !important;
}
.van-cell {
  display: flex;
  align-items: center;
}
.container {
  width: 34rem;
  margin: 1rem auto;
  margin-top: 10rem;
}
.zhuce-font {
  font-size: 1.6rem;
  color: #fecb1c;
  text-align: center;
  margin-bottom: 1rem;
  padding-top: 1rem;
}
.van-form {
  background-color: #fff;
  padding: 2rem;
  border-radius: 1rem;
}
.van-hairline--top-bottom::after,
.van-hairline-unset--top-bottom::after {
  border: none;
}
</style>